package com.liuxing.javaSpringBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * @File ParamFilter.java
 * @Auth liuxing
 * @Date 2021/8/23 10:12
 * @Email liuxing997@foxmail.com
 */
@WebFilter(filterName = "paramFilter",value = {"/*"})
public class ParamFilter  implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("====Init Filter====");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("====Do Filter====");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req){
            @Override
            public String getParameter(String name){
                String value = super.getParameter(name);
                if (StringUtils.isNotBlank(value)){
                    value = value.replaceAll("fuck","***");
                }
                return value;
            }
            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);

                //steam  api: 数组 ---list    处理数据   转化为数组
                values =   Arrays.asList(values).stream().map(item->item.replaceAll("fuck","***"))
                        .toArray(String[]::new);
                return  values;
            }
        };
        filterChain.doFilter(wrapper,resp);
    }

    @Override
    public void destroy() {
        LOGGER.debug("====Destroy Filter====");
    }
}
